<template>
  <div style="display: flex;">
    <el-button v-for="(item, index) in dataList" type="success"
               :style="styleList[index]" class="my-but" @click="myClick(index)"
               round>
      {{ item }}
    </el-button>
  </div>
</template>

<script setup>

import {onMounted, onUpdated, reactive, ref, watch} from "vue";

const myProps = defineProps({
  dataList: {
    type: Array,
    default: ()=>{
      return []
    }
  }
})

let myList = ref([{}])

const styleList = ref([])

let oldNew = 0;

const initMyList = (length)=>{
  myList.value = new Array(length);
  styleList.value = new Array(length);
  for (let i = 0; i < length; i++) {
    myList.value[i] = i;
    styleList.value[i] = {
      backgroundColor: "white",
      color: "black"
    }
  }
  styleList.value[0].backgroundColor = "red";
  styleList.value[0].color = "white";
  oldNew = 0;
}

watch(()=>myProps.dataList,(newValue)=>{
  if (newValue.length !== 0) {
    initMyList(newValue.length)
  }
},{
  //非惰性
  immediate: true,
  //深度监视
  deep: true
})

let emit = defineEmits(['meClick'])

const myClick = (index)=>{
  if (oldNew  !== index) {
    styleList.value[oldNew].backgroundColor = "white"
    styleList.value[oldNew].color = "black"
    styleList.value[index].backgroundColor = "red"
    styleList.value[index].color = "white"
    oldNew = index;
    emit("meClick",index)
  }
}



</script>

<style scoped>
.my-but{
  font-size: 18px;
  background-color: red;
  height: 40px;
  width: 90px;
  color: white;
}
</style>
